# -*- coding: utf-8 -*-

from django.http import HttpResponseNotAllowed, HttpResponseForbidden
from innervoicessite.innerword.models import User

class ViewDispatcher(object):
    ''' callback instances for every kind request.
    '''
    def __call__(self, request, *var_list, **var_dict):
        self.request = request
        self.var_list = var_list
        self.var_dict= var_dict

        # Try to locate a handler method.
        try:
            callback = getattr(self, 'do_%s' % request.method.lower())
        except AttributeError:
            # Do not use m.lstrip('do_'), because If you have string 'do_doit'
            allowed_methods = [m[3:].upper() for m in dir(self) if m.startswith('do_')] 
            #allowed_methods = map(lambda m: m.lstrip('do_').upper(), filter(lambda m: m.startswith('do_'), dir(self)))
            return HttpResponseNotAllowed(allowed_methods)

        # Check and store HTTP basic authentication, even for methods that.
        self.authenticate()

        # Call the process method and then return a response.
        return callback()

    def authenticate(self):
        # Pull the auth info out of the Authorization header.
        auth_info = self.request.META.get("HTTP_AUTHORIZATION", None)
        if auth_info and auth_info.startswith("Basic "):
            basic_info = auth_info.lstrip('Basic ')
            u, p = basic_info.decode('base64').split(':')

            try:
                real_u = User.objects.get(mail=u)

            except User.DoesNotExist:
                self.authenticated_user = None
            else:
                if p == real_u.passwd:
                    self.authenticated_user = real_u
                else:
                    slef.authenticated_user = None
        else:
            self.authenticated_user = None

    def forbidden(self):
        response = HttpResponseForbidden()
        response['WWW-Authenticate'] = 'Basic realm="myiste"'
        return response

